package apiday07.homework;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;

    //初始化
    public Client() {
        try {
            System.out.println("尝试连接服务器...");
            socket = new Socket("localhost", 8888);
            System.out.println("成功连接服务器！");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void start() {
        Scanner sc = new Scanner(System.in);
        try {
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            PrintWriter pw = new PrintWriter(osw, true);
            while (true) {
                String line = sc.nextLine();
                if ("exit".equals(line)) {
                    break;
                }
                pw.println(line);
            }
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }
}
